#include "ScriptState.h"
#include <SEngine/Script/StateLoader.h>
#include <SEngine/Ecs/EntityLoader/ActorLoader.h>
#include <SEDebug/Log/Log.h>

namespace SEngine
{
    ScriptState::ScriptState(const std::string & fileName)
    {
        m_luaState = StateLoader::GetInstance().CreateState();
        m_luaState->script_file(fileName);
    }

    void ScriptState::Attach(Actor &actor)
    {
        m_luaState->set("self", ActorLoader(actor));
        try {
            (*m_luaState)["OnLoad"]();
        } catch(const std::exception& e) {
            Log::GetInstance().Warn("Lua: {}", e.what());
        }
    }

    void ScriptState::BeforeUpdate()
    {
        try {
            (*m_luaState)["BeforeUpdate"]();
        } catch(const std::exception& e) {
            Log::GetInstance().Warn("Lua: {}", e.what());
        }
    }
    
    void ScriptState::OnUpdate(int delta)
    {
        try {
            (*m_luaState)["OnUpdate"](delta);
        } catch(const std::exception& e) {
            Log::GetInstance().Warn("Lua: {}", e.what());
        }
    }
    
    void ScriptState::AfterUpdate()
    {
        try {
            (*m_luaState)["AfterUpdate"]();
        } catch(const std::exception& e) {
            Log::GetInstance().Warn("Lua: {}", e.what());
        }
    }
}